<template>
  <div class="game-room">
    <div class="header">
      <button class="back-btn" @click="goBack">← 返回</button>
      <h2>{{ roomName }}</h2>
      <div class="header-right"></div>
    </div>

    <div class="room-content">
      <div v-if="loading" class="loading">加载中...</div>

      <div v-else class="room-info">
        <div class="info-card">
          <h3>房间信息</h3>
          <div class="info-row">
            <span>房间号:</span>
            <span>{{ roomId }}</span>
          </div>
          <div class="info-row">
            <span>玩家数:</span>
            <span>{{ currentPlayers }}/{{ maxPlayers }}</span>
          </div>
          <div class="info-row">
            <span>状态:</span>
            <span class="status" :class="status">{{ getStatusText(status) }}</span>
          </div>
        </div>

        <div class="players-card">
          <h3>玩家列表</h3>
          <div class="players-list">
            <div v-for="player in players" :key="player.id" class="player-item">
              <div class="player-avatar">{{ player.name[0] }}</div>
              <div class="player-info">
                <div class="player-name">{{ player.name }}</div>
                <div class="player-role" v-if="player.role">{{ player.role }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="actions" v-if="status === 'waiting'">
          <button class="btn btn-primary" @click="selectRole" v-if="!myRole">选择角色</button>
          <button class="btn btn-success" @click="startGame" v-if="isHost && canStart()">开始游戏</button>
          <div v-if="isHost && !canStart()" class="start-hint">
            <p v-if="players.length === 0">等待玩家加入...</p>
            <p v-else-if="players.some(p => !p.roleId)">等待所有玩家选择角色...</p>
            <p v-else-if="players.length < 2">至少需要2名玩家才能开始游戏</p>
            <p v-else>可以开始游戏</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";

export default {
  name: "GameRoom",
  setup() {
    const router = useRouter();
    const route = useRoute();
    const roomId = route.params.id;

    const loading = ref(true);
    const roomName = ref("房间");
    const currentPlayers = ref(0);
    const maxPlayers = ref(6);
    const status = ref("waiting");
    const players = ref([]);
    const myRole = ref(null);
    const isHost = ref(false);

    let pollInterval = null;

    const loadRoomInfo = async () => {
      try {
        const response = await axios.get(`/api/rooms/${roomId}`);
        if (response.data.success) {
          const room = response.data.room;
          roomName.value = room.name || `房间 ${roomId}`;
          currentPlayers.value = room.currentPlayers || 0;
          maxPlayers.value = room.maxPlayers || 6;
          status.value = room.status || "waiting";
          players.value = room.players || [];
          isHost.value = room.isHost || false;
          myRole.value = room.myRole || null;
          
          // 如果游戏已经开始，自动跳转到游戏剧本页面
          if (room.status === "playing") {
            router.push(`/room/${roomId}/game`);
          }
        }
      } catch (error) {
        console.error("加载房间信息失败:", error);
      } finally {
        loading.value = false;
      }
    };

    const selectRole = () => {
      router.push(`/room/${roomId}/role-select`);
    };

    const startGame = async () => {
      try {
        const response = await axios.post(`/api/rooms/${roomId}/start`);
        if (response.data.success) {
          // 游戏开始后，跳转到游戏剧本页面
          router.push(`/room/${roomId}/game`);
        } else {
          alert(response.data.message || "无法开始游戏");
        }
      } catch (error) {
        console.error("开始游戏失败:", error);
        alert("开始游戏失败，请稍后重试");
      }
    };

    const getStatusText = (status) => {
      const statusMap = {
        waiting: "等待中",
        playing: "游戏中",
        finished: "已结束",
      };
      return statusMap[status] || status;
    };

    const canStart = () => {
      // 检查是否有玩家
      if (players.value.length === 0) {
        return false;
      }
      // 检查所有玩家是否都选择了角色
      const allSelected = players.value.every((p) => p.roleId && p.role);
      // 检查玩家数量是否达到最小要求（至少2人，但根据剧本要求）
      const minPlayers = 2; // 最小2人
      const hasEnoughPlayers = players.value.length >= minPlayers;
      // 检查玩家数量是否不超过最大限制
      const withinMaxLimit = players.value.length <= maxPlayers.value;
      
      return allSelected && hasEnoughPlayers && withinMaxLimit;
    };

    const goBack = () => {
      router.push("/rooms");
    };

    onMounted(() => {
      loadRoomInfo();
      // 轮询更新房间信息
      pollInterval = setInterval(loadRoomInfo, 3000);
    });

    onUnmounted(() => {
      if (pollInterval) {
        clearInterval(pollInterval);
      }
    });

    return {
      roomId,
      loading,
      roomName,
      currentPlayers,
      maxPlayers,
      status,
      players,
      myRole,
      isHost,
      selectRole,
      startGame,
      getStatusText,
      canStart,
      goBack,
    };
  },
};
</script>

<style scoped>
.game-room {
  min-height: 100vh;
  background: #f5f5f5;
}

.header {
  background: white;
  padding: 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header h2 {
  font-size: 20px;
  font-weight: 600;
}

.back-btn {
  background: none;
  border: none;
  color: #667eea;
  font-size: 16px;
  cursor: pointer;
  padding: 5px 10px;
}

.header-right {
  width: 60px;
}

.room-content {
  padding: 20px;
}

.loading {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.info-card,
.players-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-card h3,
.players-card h3 {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 15px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}

.info-row:last-child {
  border-bottom: none;
}

.status {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status.waiting {
  background: #e3f2fd;
  color: #1976d2;
}

.status.playing {
  background: #fff3e0;
  color: #f57c00;
}

.status.finished {
  background: #f3e5f5;
  color: #7b1fa2;
}

.players-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.player-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.player-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: 600;
}

.player-info {
  flex: 1;
}

.player-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
}

.player-role {
  font-size: 12px;
  color: #999;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 20px;
}

.btn {
  padding: 16px 32px;
  font-size: 16px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:active {
  background: #5568d3;
  transform: scale(0.98);
}

.btn-success {
  background: #4caf50;
  color: white;
}

.btn-success:active {
  background: #45a049;
  transform: scale(0.98);
}

.start-hint {
  text-align: center;
  padding: 15px;
  background: #fff3e0;
  border-radius: 8px;
  margin-top: 15px;
}

.start-hint p {
  margin: 0;
  font-size: 14px;
  color: #f57c00;
}
</style>

